<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="name" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click.prevent="addFn">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in arr" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click.prevent="delFn(item.id)">删除</button>
            <button @click.prevent="bianFn(item.id)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      arr: [
        {
          id: 1,
          name: "坤坤",
          age: 20,
          gender: "男",
        },
      ],
      name: "",
      age: "",
      gender: "男",
      flag: "", //标记 用于区分按钮点击了是添加还是修改功能 ''表示添加功能
    };
  },
  methods: {
    addFn() {
      //添加，修改
      if (this.flag === "") {
        // 判断是否为空
        if (this.name.trim().length == 0 || this.age.trim() <= 0) {
          return;
        }
        this.arr.push({
          id: +new Date(),
          name: this.name,
          age: this.age,
          gender: this.gender,
        });
      } else {
        console.log("修改功能");
        // 修改的时候具体干啥 ==> 那输入框的值作为 flag 要修改对象的具体值
        this.flag.name = this.name;
        this.flag.age = this.age;
        this.flag.gender = this.gender;
      }
      //清空
      (this.name = "")((this.age = ""))((this.gender = "男"))(
        // 重置
        (this.flag = "")
      );
    },
    delFn(id) {
      this.arr = this.arr.filter((item) => item.id !== id);
    },
    bianFn(id) {
      //点击编辑按钮
      console.log(id);

      //回显数据  查找符合的那一项
      //findIndex 查找下标
      const obj = this.arr.find((item) => item.id === id);
      console.log(obj);

      //todo 点击编辑按钮的时候，把flag标识给修改掉，以便区分是修改功能
      // flag里面是对象，标识要做修改功能，对象是我们要修改的那个对象信息
      //记录
      //flag 是 '' 标识添加功能
      //flag 是对象 标识修改功能 flag 里面存的对象，就是我们要修改的那个对象
      this.flag = obj;

      // 修改name age sex 数据
      const { name, age, gender } = obj;
      this.name = name;
      this.age = age;
      this.gender = gender;
    },
  },
};
</script>
